//
// Created by yanhai on 2021/5/2.
//

#include <iostream>
#include <thread>
#include <unistd.h>

class TA {
public:
    TA(int &i) : m_i(i)
    {
        std::cout << "TA构造函数被执行了" << std::endl;
    }

    TA(const TA &ta) : m_i(ta.m_i)
    {
        std::cout << "TA拷贝构造函数被执行" << std::endl;
    }

    ~TA()
    {
        std::cout << "TA析构函数被执行" << std::endl;
    }

    void operator()()
    {
        std::cout << "我的线程operator()开始执行了" << std::endl;
        std::cout << "m_i=" << m_i << std::endl;
        std::cout << "sleep 2s" << std::endl;
        sleep(2);   // 确保test函数运行结束
        std::cout << "m_i=" << m_i << std::endl;
        std::cout << "我的线程operator()结束执行了" << std::endl;
    }

private:
    int &m_i;
};

std::thread *test()
{
    int i = 6;
    std::cout << "创建线程前" << std::endl;
    // 线程类的参数是一个可调用对象
    // C++中的可调用对象：函数、函数指针，lambda表达式，重载函数调用运算符的类对象，bind创建的对象
    TA ta(i);
    auto t = new std::thread(ta);
    std::cout << "创建线程后" << std::endl;
    sleep(1); // 确保创建的线程先执行
    return t;
}

int main(int argc, char **argv)
{
    auto t = test();
    t->join();
    delete t;
    return 0;
}
